<?php

namespace Biz\model\store;

use Doraemon\pockets\datebase\BaseDbModel;

class StoreCustomCategoryWiki extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'store_custom_category_wiki';

    const STATE_CANCEL = 0;//未关联
    const STATE_NORMAL = 1;//已关联
    const STATE_DEL = 9;//已删除

    public static function selectByWhere($where, $select = '*')
    {
        return self::select($select, $where);
    }

    public static function selectCountWhere($where)
    {
        return self::count('id', $where);
    }

    /**
     * @param $categoryId
     * @param $storeId
     * @param $basicId
     * @param null $sort
     */
    public static function addData($categoryId, $storeId, $basicId, $sort = null)
    {
        $info = self::getByWhere(['category_id' => $categoryId, 'store_id' => $storeId, 'basic_id' => $basicId]);
        if ($info) {
            $data = ['custom_state' => self::STATE_NORMAL];
            if (!is_null($sort)) {
                $data['sort'] = $sort;
            }
            self::updateData($data, ['category_id' => $categoryId, 'store_id' => $storeId, 'basic_id' => $basicId]);
        } else {
            $sort = empty($sort) ? 0 : $sort;
            self::insertData([
                'category_id' => $categoryId,
                'store_id' => $storeId,
                'basic_id' => $basicId,
                'sort' => $sort,
            ]);
        }
    }

    public static function getByWhere($where, $select = '*')
    {
        return self::get($select, $where);
    }

    /**
     * @param $data
     * @param $where
     * @return bool
     */
    public static function updateData($data, $where): bool
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return true;
    }

    /**
     * @param $data
     * @return false|int|mixed|string
     */
    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return self::id();
    }
}